def generate_bandpass_filter(order=100, highpass_r=10e3, highpass_c=180e-9, lowpass_r=82e3, lowpass_c=10e-9, filename="bandpass_filter.cir"):
    if order % 2 != 0:
        raise ValueError("滤波器阶数必须是偶数（等分为高通和低通）")

    highpass_order = order // 2
    lowpass_order = order // 2

    lines = []
    lines.append(f"* {order} order bindpass filter :{highpass_order} highpass + {lowpass_order}lowpass\n")

    # 高通部分
    lines.append(f"* {highpass_order}order highpass filter")
    lines.append(f"C1 in hp1 {highpass_c}")
    lines.append(f"R1 hp1 0 {highpass_r}")
    for i in range(2, highpass_order + 1):
        lines.append(f"C{i} hp{i-1} hp{i} {highpass_c}")
        lines.append(f"R{i} hp{i} 0 {highpass_r}")

    # 低通部分
    lines.append(f"\n* {lowpass_order}order lowpass filter")
    if lowpass_order == 1:
        lines.append(f"R{highpass_order + 1} hp{highpass_order} out {lowpass_r}")
        lines.append(f"C{highpass_order + 1} out 0 {lowpass_c}")
    else:
        lines.append(f"R{highpass_order + 1} hp{highpass_order} lp1 {lowpass_r}")
        lines.append(f"C{highpass_order + 1} lp1 0 {lowpass_c}")
        for i in range(2, lowpass_order):
            idx = highpass_order + i
            lines.append(f"R{idx} lp{i - 1} lp{i} {lowpass_r}")
            lines.append(f"C{idx} lp{i} 0 {lowpass_c}")

        # 最后一级低通输出为 out
        final_idx = highpass_order + lowpass_order
        lines.append(f"R{final_idx} lp{lowpass_order - 1} out {lowpass_r}")
        lines.append(f"C{final_idx} out 0 {lowpass_c}")

    lines.append(f"Vin in 0 AC 1")
    # 交流分析设置
    # lines.append("* 交流分析设置")
    lines.append(".AC LIN 10000 1Hz 10kHz")

    # 性能测量指令
    # lines.append("* 性能测量指令")
    lines.append(".MEASURE AC max_vdb MAX VDB(out)")
    lines.append(".MEASURE AC f_low WHEN VDB(out)='max_vdb-3' CROSS=1")
    lines.append(".MEASURE AC f_high WHEN VDB(out)='max_vdb-3' CROSS=2")
    lines.append(".MEASURE AC bw PARAM='f_high-f_low'")
    lines.append(".MEASURE AC f_center PARAM='sqrt(f_low*f_high)'")

    # 波形数据保存
    # lines.append("* 波形数据保存")
    lines.append(".PROBE AC VDB(out) VP(out)")
    lines.append(".OPTIONS POST")
    lines.append(".END")

    # 写入文件
    with open(filename, "w") as f:
        f.write("\n".join(lines))

    print(f"✅ 成功生成 {order} 阶带通滤波器：{filename}")

# 示例：生成 80 阶带通滤波器，传入自定义的 RC 参数
if __name__ == "__main__":
    generate_bandpass_filter(
        order=100,                # 阶数
        highpass_r=11.5e3,         # 高通电阻 (10kΩ)
        highpass_c=200e-9,       # 高通电容 (180nF)
        lowpass_r=93e3,          # 低通电阻 (82kΩ)
        lowpass_c=12e-9,         # 低通电容 (10nF)
        filename="BPF.sp"  # 输出文件名
    )
